package com.yanqu.road.server.logic.task;

import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eTaskType;
import com.yanqu.road.entity.player.UserSecretVolume;
import com.yanqu.road.entity.task.TaskInfo;
import com.yanqu.road.entity.task.UserTaskData;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.gameplayer.module.player.SecretVolumeModule;
import com.yanqu.road.server.gameplayer.module.specialserver.IceServerModule;
import com.yanqu.road.server.gameplayer.module.task.TaskModule;
import com.yanqu.road.server.logic.thread.ALiPayTask;
import com.yanqu.road.server.manger.config.ALiPayReportMgr;
import com.yanqu.road.server.manger.config.TaskMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.Date;

public class BaseTaskData {

	private static Logger logger = LogManager.getLogger(BaseTaskData.class.getName());

	protected BaseCondition baseCondition;

	private UserTaskData userTaskData;

	protected GamePlayer player;

	private int taskId;

	public BaseTaskData(BaseCondition baseCondition, UserTaskData userTaskData, GamePlayer player) {
		super();
		this.baseCondition = baseCondition;
		this.player = player;
		if (userTaskData != null) {
			this.userTaskData = userTaskData;
			this.taskId = userTaskData.getTaskId();
		}
	}

	public BaseTaskData(GamePlayer player, int taskId) {
		super();
		this.player = player;
		this.taskId = taskId;
	}

	public int getTaskId() {
		return taskId;
	}

	public UserTaskData getUserTaskData() {
		return userTaskData;
	}

	public final void playerAddTrigger(GamePlayer player) {
		if (userTaskData != null && userTaskData.getState() == 1) {
			// 已完成不监听
			return;
		}
		addTrigger();
	}

	public void addTrigger() {
		if (null != baseCondition) {
			baseCondition.addTrigger(player);
		}
	}

	public void removeTrigger() {
		if (null != baseCondition) {
			baseCondition.removeTrigger(player);
		}
	}

	public final boolean canCompleted() {
		if (userTaskData == null) {
			return false;
		}
		if (userTaskData.getState() != 0) {
			return false;
		}
		if(null != baseCondition) {
			return baseCondition.isCompleted(player);
		}
		return true;
	}

	public final void reset() {
		if (userTaskData == null) {
			return;
		}
		userTaskData.setState(0);
		if(null != baseCondition){
			baseCondition.setValue(BigInteger.ZERO);
		}
	}

	public final boolean isResetDailyTask() {
		if (userTaskData == null) {
			return false;
		}
		return DateHelper.getDate0AM(userTaskData.getEndTime()).compareTo(DateHelper.getDate(0, 0, 0)) != 0;
	}

	public final boolean isResetWeekTask() {
		if (userTaskData == null) {
			return false;
		}
		if (DateHelper.getDate0AM(userTaskData.getEndTime()).compareTo(DateHelper.getNextWeekMonday(DateHelper.getDate(0, 0, 0))) != 0) {
			return true;
		}
		return false;
	}

	public final boolean isResetCustomTask(long time, int day) {
		if (userTaskData == null) {
			return false;
		}
		if (DateHelper.getDate0AM(userTaskData.getEndTime()).compareTo(DateHelper.getNextResetDate(new Date(time), day)) != 0) {
			return true;
		}
		return false;
	}

	// 重置日常任务
	public final void resetDailyTask() {
		if (userTaskData == null) {
			return;
		}
		if (isResetDailyTask()) {
			userTaskData.setState(0);
			userTaskData.setEndTime(DateHelper.getDate(0, 0, 0));
			userTaskData.setValue(BigInteger.ZERO);
			if (null != baseCondition) {
				baseCondition.setValue(BigInteger.ZERO);
				baseCondition.addTrigger(player);
			}
		}
	}

	// 重置七日任务
	public final void resetWeekTask(boolean force) {
		if (userTaskData == null) {
			return;
		}
		if (force || DateHelper.getDate0AM(userTaskData.getEndTime()).compareTo(DateHelper.getNextWeekMonday(DateHelper.getDate(0, 0, 0))) != 0) {
			userTaskData.setState(0);
			userTaskData.setEndTime(DateHelper.getNextWeekMonday(DateHelper.getDate(0, 0, 0)));
			userTaskData.setValue(BigInteger.ZERO);
			userTaskData.setFinishTime(0);
			if (null != baseCondition) {
				baseCondition.setValue(BigInteger.ZERO);
				baseCondition.addTrigger(player);
			}
		}
	}

	//定制重置
	public final void resetCustomTask(long time, int day) {
		if (userTaskData == null) {
			return;
		}
		if (DateHelper.getDate0AM(userTaskData.getEndTime()).compareTo(DateHelper.getNextResetDate(new Date(time), day)) != 0) {
			userTaskData.setState(0);
			userTaskData.setEndTime(DateHelper.getNextResetDate(new Date(time), day));
			userTaskData.setValue(BigInteger.ZERO);
			userTaskData.setFinishTime(0);
			if (null != baseCondition) {
				baseCondition.setValue(BigInteger.ZERO);
				baseCondition.addTrigger(player);
			}
		}
	}

	public final void resetKuangTask() {
		if (userTaskData == null) {
			return;
		}
		userTaskData.setState(0);
		userTaskData.setValue(BigInteger.ZERO);
		userTaskData.setFinishTime(0);
		if (null != baseCondition) {
			baseCondition.setValue(BigInteger.ZERO);
			baseCondition.addTrigger(player);
		}
	}

	/**
	 * userTaskData则初始化
	 */
	public final void initUserTaskData() {
		if (this.userTaskData != null) {
			// 已存在不处理
			return;
		}
		TaskInfo taskInfo = TaskMgr.getTaskInfoById(taskId);
		if (taskInfo != null) {
			this.userTaskData = player.getModule(TaskModule.class).initUserTaskData(taskInfo);
		}
	}

	public final void changeValue() {
		if (userTaskData == null) {
			this.initUserTaskData();
		}
		saveData();
		if (player != null) {
			player.getModule(TaskModule.class).changeValue(this);
		}
	}

	public void finishBeautyTask(){
		finish();
		//其他操作在这里加
	}

	// 完成支付宝任务上报
	public void finishALiPayTask(){
		if (userTaskData == null) {
			return;
		}
		String appExt = "";
		if (player.getAppExt().containsKey("app_ext")) {
			appExt = player.getAppExt().getString("app_ext");
		}
		ALiPayReportMgr.alipayReport(player, appExt, baseCondition, userTaskData);
	}

	// 完成美团任务上报
	public void finishMeiTuanTask(){
		if (userTaskData == null) {
			return;
		}
		String channel_uid = "";
		if (player.getAppExt().containsKey("channel_uid")) {
            channel_uid = player.getAppExt().getString("channel_uid");
		}
		if(StringUtils.isNullOrEmpty(channel_uid)){
//		    logger.error("{} 美团任务缺失 channel_uid", player.getUserId());
		    return;
        }
		ALiPayReportMgr.meiTuanReport(player, channel_uid, baseCondition, userTaskData);
	}

	/**
	 * 完成任务领取奖励
	 */
	public final void finish() {
		if (userTaskData == null) {
			return;
		}
		TaskInfo taskInfo = TaskMgr.getTaskInfoById(userTaskData.getTaskId());
		Property reward = new Property();
		if(userTaskData.getTaskType() == eTaskType.SecretVolumeLevel.getValue()){
			UserSecretVolume userSecretVolume = player.getModule(SecretVolumeModule.class).getUserSecretVolume();
			if(userSecretVolume != null){
				reward = taskInfo.getSecretVolumeReward(userSecretVolume.getNo());
			}
		}else{
			reward = taskInfo.getReward();
		}
		// 添加奖励
		player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Task, eLogMoneyType.TaskGetReward);
		userTaskData.setState(1);
		userTaskData.setFinishTime(System.currentTimeMillis() / 1000);
		player.getModule(TaskModule.class).resetActive();
		if(taskInfo.getIntegral() > 0) {
			if (taskInfo.getType() == eTaskType.SevenDay.getValue()) {
				player.getModule(TaskModule.class).addSevenDayActive(taskInfo.getIntegral());
			} else if (taskInfo.getType() == eTaskType.Daily.getValue()) {
				player.getModule(TaskModule.class).addTaskActive(taskInfo.getIntegral());
			}
		}
		//家具目标最后一件
		if (taskInfo.getType() == eTaskType.WingRoomUnLock.getValue()) {
			player.getModule(PlayerModule.class).checkWingRoomSystemOpen();
		}
		// 寒冬特殊任务
		if (taskInfo.getType() == eTaskType.IceServerSubTask.getValue()) {
			if (baseCondition.getTaskConditionInfo().getType() == eGamePlayerEventType.IceServerAddSatiation.getValue()) {
				// 温粥提升饱腹度
				player.getModule(IceServerModule.class).addSatiation(baseCondition.getTaskConditionInfo().getParamList().get(1));
			} else if (baseCondition.getTaskConditionInfo().getType() == eGamePlayerEventType.IceServerAddTemperature.getValue()) {
				// 提升温度
				player.getModule(IceServerModule.class).addTemperature(baseCondition.getTaskConditionInfo().getParamList().get(2));
			} else if (baseCondition.getTaskConditionInfo().getType() == eGamePlayerEventType.IceServerUpgradeBuilding.getValue()) {
				// 升级所有建筑
				player.notifyListener(eGamePlayerEventType.IceServerUpgradeAllBuilding.getValue());
			}
		}
		LogMgr.addLogTaskReward(player.getUserId(), taskInfo.getTaskId(), taskInfo.getIntegral(), PropertyHelper.parsePropertyToString(reward));
		removeTrigger();
	}

	public final void saveData() {
		if (userTaskData == null) {
			return;
		}
		if(null != baseCondition) {
			userTaskData.setValue(baseCondition.getValue());
		}
	}

	public final void retainData(UserTaskData preTaskData) {
		if (preTaskData == null) {
			return;
		}
		if (null != baseCondition) {
			baseCondition.setValue(preTaskData.getValue());
		}
	}

	public GamePlayer getGamePlayer() {
		return player;
	}

	public BaseCondition getBaseCondition() {
		return baseCondition;
	}

	public void setBaseCondition(BaseCondition baseCondition) {
		this.baseCondition = baseCondition;
	}

	public boolean isNeedDayReset() {
		if (userTaskData == null) {
			return false;
		}
		if (userTaskData.getTaskType() == eTaskType.Daily.getValue()
				|| userTaskData.getTaskType() == eTaskType.WeekendSystem.getValue()
				|| userTaskData.getTaskType() == eTaskType.ALiPayTask.getValue()
				|| userTaskData.getTaskType() == eTaskType.MeiTuanTask.getValue()
				|| userTaskData.getTaskType() == eTaskType.ALiPayFiveBlessingsTask.getValue()) {
			return true;
		}
		return false;
	}
}
